﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Services.Service.Customer;
using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Web.UI;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Web.Helper;
using System.Configuration;
using System.IO;
using NPOI.XSSF.UserModel;
using KingsSharp.Common.Data;
using CRM.Admin.Contracts.Contract.Sys;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;

namespace CRM.Admin.Areas.Customer.Controllers
{
    public class VarietyController : Controller
    {

        public const string CUSTOMER_FILEPATH = "BaseCustomerfiles//";
        public IVarietyService VarietyService { get; set; }
        public IDictionaryService DictionaryService { get; set; }
        public ActionResult VarietyAdd(Guid CustomerId, string GuidId)
        {
            Guid Id = Guid.Empty;
            if (GuidId != "null")
            {
                Id = new Guid(GuidId);
            }
            else
            {
                Id = Guid.NewGuid();
            }



            var result = VarietyService.Varietys.FirstOrDefault(a => a.Id == Id).MapTo<VarietyDto>();
            ViewBag.CustomerId = CustomerId;
            if (result == null)
            {
                result = new VarietyDto();
            }
            return View(result);
        }
        public ActionResult VarietyEdit(Guid CustomerId, Guid Id)
        {
            var result = VarietyService.Varietys.FirstOrDefault(a => a.Id == Id).MapTo<VarietyDto>();
            ViewBag.CustomerId = CustomerId;
            ViewBag.Id = Id;
            return View(result);
        }
        public ActionResult VarietyInsert(VarietyDto varietyDto)
        {
            varietyDto.CheckNotNull("varietyDto");

            var result = VarietyService.Insert(varietyDto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "攀钢品种 “{0}” 的品种需求添加成功。".FormatWith(varietyDto.BreedName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult VarietyDelete(Guid UserId)
        {
            UserId.CheckNotEmpty("UserId");
            Guid[] id = new Guid[] { UserId };
            var result = VarietyService.Delete(id);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "品种需求删除成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult VarietyUpdate(VarietyDto dto)
        {
            dto.CheckNotNull("dto");
            var result = VarietyService.Update(dto);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "品种需求修改成功。";
            }
            return Json(new AjaxResult(msg, msgType));
        }
        #region 导入Excel
        /// <summary>
        /// 导入Excel需求品种需求
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public ActionResult VarietyExcelInsert(Guid CustomerId)
        {
            UploaderResult result = null;
            int r = 0;

            try
            {
                string path = CUSTOMER_FILEPATH;
                result = new WebUploader().Process(Request, path, file => Guid.NewGuid().ToString() + "_" + file.FileName);

                var list = new List<VarietyDto>();
                var filePath = result.Path;

                if (filePath == null) return Json("");
                // var staticdir = ConfigurationManager.AppSettings["excelPath"];

                var savepath = "//" + result.Path;
                var stream = new FileStream(Server.MapPath(savepath), FileMode.Open, FileAccess.Read);

                using (stream)
                {
                    IWorkbook excel = null;
                    if (result.Path.IndexOf(".xlsx") > 0)
                    {
                        excel = new XSSFWorkbook(stream);
                    }
                    else if (result.Path.IndexOf(".xls") > 0)
                    {
                        excel = new HSSFWorkbook(stream);
                    }
                    var sheet = excel.GetSheetAt(0);
                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        r = i + 1;

                        var row = sheet.GetRow(i);


                        var model = new VarietyDto();
                        model.Id = Guid.NewGuid();
                        model.CustomerId = CustomerId;
                        if (row.GetCell(0) == null || string.IsNullOrWhiteSpace(row.GetCell(0).ToString()))
                        {
                            continue;
                        }
                        if (row.GetCell(0) != null)
                        {
                            model.ParticularYear = Convert.ToInt32(row.GetCell(0).ToString());
                        }
                        if (row.GetCell(1) != null)
                        {
                            model.Month = Convert.ToInt32(row.GetCell(1).ToString());
                        }
                        if (row.GetCell(2) != null)
                        {
                            model.DemandSourcesName = row.GetCell(2).ToString();
                        }
                        if (row.GetCell(3) != null)
                        {
                            model.MaterialMade = row.GetCell(3).ToString();
                        }
                        if (row.GetCell(4) != null)
                        {
                            model.MaterialSpecs = row.GetCell(4).ToString();
                        }
                        if (row.GetCell(5) != null)
                        {
                            model.MaterialWeight = Convert.ToDecimal(row.GetCell(5).ToString());
                        }
                        if (row.GetCell(6) != null)
                        {
                            model.NowNeedWeight = Convert.ToDecimal(row.GetCell(6).ToString());
                        }
                        if (row.GetCell(7) != null)
                        {

                            model.MaterialHeight = Convert.ToDecimal(row.GetCell(7).ToString());
                        }
                        if (row.GetCell(8) != null)
                        {
                            model.MaterialThickness = row.GetCell(8).ToString();
                        }
                        if (row.GetCell(9) != null)
                        {
                            model.MaterialWidth = Convert.ToDecimal(row.GetCell(9).ToString());
                        }
                        if (row.GetCell(10) != null)
                        {
                            var breeName = row.GetCell(10).ToString();
                            var dictionary = DictionaryService.ItemDictionary.FirstOrDefault(a => a.Name.Equals(breeName));
                            if (dictionary != null)
                            {
                                model.BreedId = dictionary.Id;
                            }
                            model.BreedName = row.GetCell(10).ToString();

                        }
                        if (row.GetCell(11) != null)
                        {
                            model.PGFCoverWeight = Convert.ToDecimal(row.GetCell(11).ToString());
                        }
                        if (row.GetCell(12) != null)
                        {
                            model.PGFAlreadySupplyWeight = Convert.ToDecimal(row.GetCell(12).ToString());
                        }
                        if (row.GetCell(13) != null)
                        {
                            model.XGFCoverWeight = Convert.ToDecimal(row.GetCell(13).ToString());
                        }
                        if (row.GetCell(14) != null)
                        {
                            model.XGFAlreadySupplyWeight = Convert.ToDecimal(row.GetCell(14).ToString());
                        }

                        //if (row.GetCell(15)!=null)
                        //{
                        //    model.PGCoverWeight = Convert.ToDecimal(row.GetCell(15).ToString());
                        //}
                        //if (row.GetCell(16)!=null)
                        //{
                        //    model.PGAlreadySupplyWeight = Convert.ToDecimal(row.GetCell(16).ToString());
                        //}
                        //if (row.GetCell(17)!=null)
                        //{
                        //    model.NewProductProfiles = row.GetCell(17).ToString();
                        //}
                        //if (row.GetCell(18)!=null)
                        //{
                        //    model.DevelopmentProfiles = row.GetCell(18).ToString();
                        //}
                        //if (row.GetCell(19)!=null)
                        //{
                        //    model.NewUserProfiles = row.GetCell(19).ToString();
                        //}
                        //if (row.GetCell(20)!=null)
                        //{
                        //    model.SaleFeasibility = row.GetCell(20).ToString();
                        //}
                        //if (row.GetCell(21)!=null)
                        //{
                        //    model.NoCooperateProfiles = row.GetCell(21).ToString();
                        //}
                        //if (row.GetCell(22) != null)
                        //{
                        //    model.PriceMoreEvaluate = row.GetCell(22).ToString();
                        //}
                        //if (row.GetCell(23) != null)
                        //{
                        //    model.NowSupply = row.GetCell(23).ToString();
                        //}
                        //if (row.GetCell(24) != null)
                        //{
                        //    model.YearNeedProfiles = row.GetCell(24).ToString();
                        //}
                        //if (row.GetCell(25) != null)
                        //{
                        //    model.NextYearNeedProfiles = row.GetCell(25).ToString();
                        //}
                        //if (row.GetCell(26) != null)
                        //{
                        //    model.NextNeedProfiles = row.GetCell(26).ToString();
                        //}
                        //if (row.GetCell(27) != null)
                        //{
                        //    model.MaterialProfiles = row.GetCell(27).ToString();
                        //}
                        //if (row.GetCell(28) != null)
                        //{
                        //    model.GetMaterialUser = row.GetCell(28).ToString();
                        //}
                        list.Add(model);

                    }
                    var res = VarietyService.Insert(list.ToArray());

                    if (res.ResultType == OperationResultType.Error)
                    {
                        result.Message = res.Message;
                    }

                    if (res.ResultType == OperationResultType.Success)
                    {
                        result.Message = res.Message;
                    }
                }


            }
            catch (Exception ex)
            {

                result.Message = "第" + r + "行数据格式有误";
            }
            return Json(result);
        }
        #endregion
    }
}